import NavBar from '@/components/NavBar'
import ArticleItem from '@/pages/Home/components/ArticleItem'
import { RootType } from '@/store'
import { getSearchResults } from '@/store/actions/search'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useLocation } from 'react-router-dom'
import { InfiniteScroll } from 'antd-mobile'
import styles from './index.module.scss'

let page = 1

const SearchResult = () => {
  const dispatch = useDispatch()
  const location = useLocation()
  const search = new URLSearchParams(location.search)
  const key = search.get('key')!
  // 搜索结果
  const results = useSelector((state: RootType) => state.search.results)
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)
  const loadMore = async () => {
    if (loading) return
    setLoading(true)
    await dispatch(getSearchResults(key, page) as any)
    page = page + 1
    setLoading(false)
    if (page > 5) {
      setHasMore(false)
    }
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="navBar">搜索结果</NavBar>

      <div className="article-list">
        {results.map((item, index) => (
          <ArticleItem article={item} key={index}></ArticleItem>
        ))}
      </div>
      {/* 上拉加载更多 */}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default SearchResult
